Skip to main content

About SSR

· 2 min read
Imagine Chiu
Front End Engineer @ Bearests

In the past few days, I updated some examples to the homepage and put them on Cloudflare via SSG. I found some strange problems. They work fine in development mode, but they don't work as expected when I page build them to the cloud.

  • Using window will cause an error because there is no such variable in Nodejs.
  • Avoid SSR rendering errors during CSR hydration.
  • Originally, the ID was bound to . The style of bear-carousel_id was specified in the tag, but if the component is re-rendered, it will cause a new ID to be generated, and the style will not be set.
Error: Hydration failed because the initial UI does not match what was rendered on the server.

What changes have been made?

  • The window part has been changed to GlobalThis.window. It is not possible to use window-related items in the constructor, so there will be some changes in the logic split. Use useState in useEffect to update the state to determine if it is CSR (if it is a class component, it is this.setState and componentDidMount), and add isClientOnly to the parts that will use window. ce0537c4
  • Instead of using the ID to set the style, change it to the CSS variable method so that the style css file can use it, and delete the dependency on ulid 9b438c3